//
//  HJComposeViewController.swift
//  Weibo
//
//  Created by 韩佳 on 16/4/25.
//  Copyright © 2016年 ddg. All rights reserved.
//

import UIKit
import SVProgressHUD

class HJComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }
    //选择系统图片
    private func selectImage(){
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        self.presentViewController(imagePicker, animated: true, completion: nil)
        
    }
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setNav()
        view.addSubview(textView)
        view.addSubview(toolbar)
        textView.addSubview(pictureView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
        toolbar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(100)
            make.leading.equalTo(10)
            make.width.equalTo(view).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    private func setNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "backClicked")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = tilteView
        
        
    }
    //监听键盘frame变化调用方法,调整toolbar高度
    @objc private func keyboardDidChange(notifi:NSNotification){
        let rect = (notifi.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(rect.origin.y - ScreenHeight)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    @objc private func backClicked(){
        textView.resignFirstResponder()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    //发送按钮点击方法
    @objc private func sendBtnClick(){
        if pictureView.hidden{
            update()
        }else{
            upload()
        }
    }
    private func switchKeyboard(){
        //每次点击在文字键盘和表情键盘中切换 textView.inputView == nil表示系统键盘
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        
        textView.reloadInputViews()
        toolbar.isSystemKeyboard = (textView.inputView == nil)
        if !textView.isFirstResponder(){
            textView.becomeFirstResponder()
        }
    }
    //发文字微博
    private func update(){
        let URLString = "https://api.weibo.com/2/statuses/update.json"
        let params = [
            "access_token": HJUserAccountViewModel.shareAccount.accessToken ?? "",
            "status": textView.text
        ]
        HJNetworkTools.shareTools.request(HJRequestMethod.Post, urlString: URLString, parameters: params) { (responseObject, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    //发图片微博
    private func upload(){
        let URLString = "https://upload.api.weibo.com/2/statuses/upload.json"
        let params = [
            "access_token": HJUserAccountViewModel.shareAccount.accessToken ?? "",
            "status": textView.text!
        ]
        let data = UIImagePNGRepresentation(pictureView.images.first!)!
        HJNetworkTools.shareTools.upload(URLString, parameters: params, datas: ["pic": data]) { (responseObject, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    //懒加载控件
    private lazy var emoticonKeyboard: HJEmoticonKeyboard = {
        let keyboard = HJEmoticonKeyboard()
        keyboard.frame.size = CGSize(width: ScreenWidth, height: 216)
        return keyboard
    }()
    private lazy var pictureView:HJComposePictureView = { [weak self] in
        let view = HJComposePictureView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        view.selectItemClosure = {
           self?.selectImage()
        }
        return view
    }()
    
    private lazy var toolbar: HJComposeToolBar = {
        let toolbar = HJComposeToolBar(frame: CGRectZero)
        toolbar.buttonClickClosure = { (type:HJComposeToolBarButtonType)->() in
            print(type)
            switch type {
            case .Picture:
                self.selectImage()
                break
            case .Mention:
                break
            case .Trend:
                break
            case .Emoticon:
                self.switchKeyboard()
                break
            case .Add:
                break
                
            }
        }
        return toolbar
    }()
    
    private lazy var textView:HJTextView = {
        let textView = HJTextView()
        textView.delegate = self
        textView.font = UIFont.systemFontOfSize(16)
        textView.placeholder = "发现新鲜事..."
        //拖动时键盘消失
        textView.keyboardDismissMode = .OnDrag
        textView.alwaysBounceVertical = true
        return textView
    
    }()
    
    private lazy var rightButton:UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "sendBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        button.setTitle("发送", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        button.frame.size = CGSize(width: 45, height: 28)
        return button
    
    }()
    
    private lazy var tilteView:UILabel = {
        let label = UILabel()
        label.textColor = UIColor.blackColor()
        label.font = UIFont.systemFontOfSize(14)
        label.numberOfLines = 0
        label.textAlignment = .Center
        if let name = HJUserAccountViewModel.shareAccount.account?.name {
            let text = "发微博\n\(name)"
            let range = (text as NSString).rangeOfString(name)
            let attruText = NSMutableAttributedString(string: text)
            attruText.addAttributes([NSForegroundColorAttributeName:UIColor.grayColor(),NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
            label.attributedText = attruText
            
        }else{
            label.text = "发微博"
        }
        label.sizeToFit()
        return label
    }()
}
// MARK: - textView代理
extension HJComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
// MARK: - pickimageView代理
extension HJComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        let img = image.scaleToWidth(600)
//        let data = UIImagePNGRepresentation(img)
        
//        data?.writeToFile("/Users/hanjia/Desktop/\(random() / 3).png", atomically: true)
        pictureView.addImage(img)
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
}
